import React ,{useEffect,useState}from 'react';
import { Modal, Button,Upload, message, Rate,Table, Space} from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import {getUrl,putUrl,deleteUrl,postUrl} from '../../utils/request';
import './goods.css'
const Goods=()=>{
    let ModalText='sd';
    const [visible, setVisible] = useState(false)
    const [visible1, setVisible1] = useState(false)
    const [confirmLoading, setConfirmLoading] = useState(false)
    const [loading, setLoading] = useState(false)
    const [imageUrl, setImageUrl] = useState('')
    const [value, setValue] = useState(3);
    const [values, setValues] = useState(0);
    const [list, setList] = useState([]);
    const [value1, setValue1] = useState('')
    const [value2, setValue2] = useState('')
    const [value3, setValue3] = useState('');
    const [editList, setEditList] = useState([])
    const [descs, setDescs] = useState('')
    const [detail, setDetail] = useState('')
    const [name, setName] = useState('')
    //星星评级
    const hanDleChanges =(value: any) => {
      setValue(value);
    };
    const handleChanges1 =(values: any) => {
      setValues(values);
    };
    
    //上传图片
    const getBase64=(img:any, callback:any)=> {
      const reader = new FileReader();
      reader.addEventListener('load', () => callback(reader.result));
      reader.readAsDataURL(img);
    }
    const beforeUpload=(file:any)=> {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
      }
      return isJpgOrPng && isLt2M;
    }
    const handleChange = (info:any) => {
      console.log(info.file.status)
      if (info.file.status === 'uploading') {
        setLoading(true)
        return;
      }
      if (info.file.status === 'done') {
        getBase64(info.file.originFileObj, (imageUrl: any) =>{
              setImageUrl(imageUrl)
              setLoading(false)
           }   
        );
      }
    };
    //对话框
    const add=()=>{
        setVisible(true)
    }
    const handleOk = () => {
        postUrl('http://localhost:3333/admin/api/rest/items',{
          name:value1,
          star:value,
          detail:value3,
          desc:value2
        }).then((res:any)=>{
          if(res.status===200){
            message.success('添加成功');
            setValue(0)
            setValue1('')
            setValue2('')
            setValue3('')
          }
        })
        getUrl("http://localhost:3333/admin/api/rest/items?pagenum=1&pagesize=50", {
          pagenum: 1,
          pagesize: 50,
      }).then((res: any) => {
          setList(res.data.data)
      })
        ModalText= 'The modal will be closed after two seconds'
        setConfirmLoading(true)
        setTimeout(() => {
            setVisible(false)
            setConfirmLoading(false)
        }, 10);
      };
    
    const handleCancel = () => {
        setVisible(false)
      };
      const uploadButton = (
        <div>
          {loading ? <LoadingOutlined /> : <PlusOutlined />}
          <div style={{ marginTop: 8 }}>Upload</div>
        </div>
      );
      useEffect(() => {
        getUrl("http://localhost:3333/admin/api/rest/items?pagenum=1&pagesize=50", {
            pagenum: 1,
            pagesize: 50,
        }).then((res: any) => {
            setList(res.data.data)
        })
    }, [])
    //编辑
    const showModal=(text:any)=>{
      setVisible1(true)
      putUrl(`http://localhost:3333/admin/api/rest/items/${text._id}`,{
        _id:text._id,
        name:name,
        desc:descs,
        detail:detail,
        star:values,
      }).then((res:any)=>{
        console.log(res.data);
        setEditList(res.data)
      })
    }
      const handleOk2 =(text:any) => {
      setVisible1(false)
      console.log(text._id)
      putUrl(`http://localhost:3333/admin/api/rest/items/${text._id}`,{
        _id:text._id,
        name:name,
        desc:descs,
        detail:detail,
        star:values
      }).then((res:any)=>{
        console.log(res);
        if(res.data._id===text._id){
          console.log(res.data._id,text._id)
          setName(res.data.name)
          setDescs(res.data.desc)
          setDetail(res.data.detail)
          setValues(res.data.star)
          setEditList(res.data)
        }
        
      })
      getUrl("http://localhost:3333/admin/api/rest/items?pagenum=1&pagesize=50", {
              pagenum: 1,
              pagesize: 50,
          }).then((res: any) => {
              setList(res.data.data);
              if(res.status===200){
                message.success('编辑成功');
              }
          })
    };  
    const handleCancel2 = (e:any) => {
      setVisible1(false)
    };
    const columns = [
      { title: '序号', dataIndex: 'key', key: 'key',className:'aaa'},
      { title: '装备名称', dataIndex: 'name', key: 'name',className:'aaa' },
      {title: '图标', render: (text: any, record: any[]) => (
          <Space size="middle">
            <img src={(record as any).icon} alt="" />
          </Space>),
        key: 'icon',
        className:'aaa'
      },
      {title: '图标',dataIndex: 'star',key: 'star',className:'aaa'},
      {title: '操作',key: 'action', className:'aaa',
        render: (text:any, record:any[]) => (
          <Space size="middle">
            <>
        <Button type="primary" onClick={()=>{showModal(text)}}>
           编辑
        </Button>
        <Modal
          title="编辑装备"
          visible={visible1}
          onOk={()=>handleOk2(text)}
          onCancel={handleCancel2}>
          <li style={{width:'100%',display:'flex',justifyContent:'space-around',marginBottom:'15px'}}>
            <span>物品名称</span>
            <input type="text" placeholder='请输入物品名称' defaultValue={(editList as any).name} style={{outline:'none',border:'1px solid #ccc',width:'380px',borderRadius:'3px'}}
               onChange={(e)=>{setName(e.target.value); console.log(e.target.value)}}/>
          </li>
          <li style={{width:'100%',display:'flex',justifyContent:'space-around',marginBottom:'15px'}}>
          <span>物品图标</span>
          <img src={(editList as any).icon} alt="" style={{marginRight:'309px'}}/>
          </li>
          <li style={{marginBottom:'15px'}}>
            <span style={{marginRight:'5px',marginLeft:'10px'}}>星级</span>
          <span><Rate onChange={handleChanges1} value={(editList as any).star}style={{marginRight:'5px'}}/>{(editList as any).star}</span>
          </li>
          <li style={{width:'100%',display:'flex',justifyContent:'space-around',marginBottom:'15px'}}>
            <span>物品简介</span>
            <input type="text" placeholder='请输入物品简介' defaultValue={(editList as any).desc} style={{outline:'none',border:'1px solid #ccc',width:'380px',borderRadius:'3px'}}
               onChange={(e)=>{setDescs(e.target.value)}}/>
          </li>
          <li style={{width:'100%',display:'flex',justifyContent:'space-around',marginBottom:'15px'}}>
            <span>物品详情</span>
            <input type="text" placeholder='请输入物品详情'defaultValue={(editList as any).detail}  style={{outline:'none',border:'1px solid #ccc',width:'380px',borderRadius:'3px'}}
                onChange={(e)=>{setDetail(e.target.value)}}/>
          </li>
        </Modal>
      </>
          <Button type="primary" danger onClick={()=>{
             deleteUrl(`http://localhost:3333/admin/api/rest/items/${text._id}`)
             getUrl("http://localhost:3333/admin/api/rest/items?pagenum=1&pagesize=50", {
              pagenum: 1,
              pagesize: 50,
          }).then((res: any) => {
              setList(res.data.data);
              if(res.status===200){
                message.success('删除成功');
              }
          })
          }}>删除</Button>
          </Space>
        ),
        },
    ];
    const data: { key: number; name: any; star: any; desc: any; detail: any; icon: any;_id:any }[] = [];
    list.forEach((item,index)=>{
      data.push({
        key: index+1,
        name: (item as any).name,
        star:(item as any).star,
        desc: (item as any).desc,
        detail:(item as any).detail,
        icon:(item as any).icon,
        _id:(item as any)._id
      });
    }) 
    return(
        <div>
          <div style={{width:'100px'}}>
        <Button type="primary" onClick={()=>{
          add()
        }}>
          + 添加装备
        </Button>
        <Modal
          title="添加装备"
          visible={visible}
          onOk={handleOk}
          confirmLoading={confirmLoading}
          onCancel={handleCancel}
        >
          <li style={{width:'100%',display:'flex',justifyContent:'space-around',marginBottom:'15px'}}>
            <span>物品名称</span>
            <input type="text" placeholder='请输入物品名称' style={{outline:'none',border:'1px solid #ccc',width:'380px',borderRadius:'3px'}}
                onChange={(e:any)=>{setValue1(e.target.value)}}/>
          </li>
          <li style={{width:'100%',display:'flex',justifyContent:'space-around',marginBottom:'15px'}}>
          <span>物品图标</span>
           <div style={{width:'380px'}}>
           <Upload
            name="avatar"
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
            beforeUpload={beforeUpload} 
            onChange={handleChange}>
        {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
      </Upload>
           </div>
          </li>
          <li style={{marginBottom:'15px'}}>
            <span style={{marginRight:'5px',marginLeft:'10px'}}>星级</span>
          <span><Rate onChange={hanDleChanges} value={value} style={{marginRight:'5px'}}/>{value}</span>
          </li>
          <li style={{width:'100%',display:'flex',justifyContent:'space-around',marginBottom:'15px'}}>
            <span>物品简介</span>
            <input type="text" placeholder='请输入物品简介' style={{outline:'none',border:'1px solid #ccc',width:'380px',borderRadius:'3px'}}
                onChange={(e:any)=>{setValue2(e.target.value)}}/>
          </li>
          <li style={{width:'100%',display:'flex',justifyContent:'space-around',marginBottom:'15px'}}>
            <span>物品详情</span>
            <input type="text" placeholder='请输入物品详情' style={{outline:'none',border:'1px solid #ccc',width:'380px',borderRadius:'3px'}}
                 onChange={(e:any)=>{setValue3(e.target.value)}}/>
          </li>
        </Modal>
      </div>
      <Table
    columns={columns}
    expandable={{      
      expandedRowRender: (record)=> <div><p style={{ margin: 0,textAlign:'center'}}>{(record as any).desc}</p>
      <p style={{ margin: 0,textAlign:'center'}}>{(record as any).detail}</p></div>,
      rowExpandable: record => (record as any).name !== 'Not Expandable',
      }}
    dataSource={(data as any)}
  />
        </div>       
    )  
}

export default Goods;